﻿using System;
using UnityEngine.EventSystems;
using static UI.UIElementHandlers;
namespace UI
{
    public class UIElement : UIBehaviour
    {
        public UIContainer Parent { get; internal set; }

        public UIState State { get; internal set; }

        protected override void Awake()
        {
            base.Awake();
            UpdateParent();
        }

        protected override void OnTransformParentChanged()
        {
            base.OnTransformParentChanged();
            UpdateParent();
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
            var parent = Parent;
            if (parent != null)
            {
                parent.RemoveElement(this);
                Parent = null;
            }
        }

        public void Open()
        {
            UIElementHandlers.Open(this);
        }
        
        public void Freez()
        {
            UIElementHandlers.Freez(this);
        }

        public void Close()
        {         
            UIElementHandlers.Close(this);
        }

        private void UpdateParent()
        {
            var root = Parent;
            if (root != null)
            {
                root.RemoveElement(this);
                root = null;
            }
            var parent = transform.parent;
            while (parent != null)
            {
                root = parent.GetComponent<UIContainer>();
                if (root != null)
                {
                    root.AddElement(this);
                    break;
                }
                parent = parent.parent;
            }
            Parent = root;
        }

    }


}
